<script lang="ts" setup>
import Selector from "@/components/Selector.vue";
import Inputter from "@/components/Inputter.vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { onMounted, reactive, ref } from 'vue';
import Password from "@/components/Password.vue";
import instance from '@/utils/request';
import { useAdminStore } from "@/stores/admin";
import router from "@/router/router";

// 管理员用户信息修改页面
onMounted(() => {
  init();
});

const admin = useAdminStore();

let user_id = ref("");
let user_name = ref("");
let user_password = ref("");
let user_password_again = ref("");
let customer_phone = ref("");

let dialogVisible = ref(false);
let dialogVisibleUpdate = ref(false);
let dialogVisibleAdd = ref(false);
let dialogMessage = ref("");

// 搜索
const user_id_select = ref("");
const user_name_select = ref("");
const customer_name_select = ref("");
const customer_sex_select = ref("全部");
const customer_phone_select = ref("");
const customer_id_select = ref("");
const user_password_select = ref("");
const user_status_select = ref("全部");

// 性别的下拉框（查询）
const customer_sex_options = [
  { value:'全部', label:'全部' },
  { value:'男', label:'男' },
  { value:'女', label:'女' }
];

// 性别的下拉框（表单）
const customer_sex_form_options = [
  { value: '男', label: '男' },
  { value: '女', label: '女' }
]

// 状态的下拉框（查询）
const user_status_options = [
  { value:'全部', label:'全部' },
  { value:'在线', label:'在线' },
  { value:'离线', label:'离线' },
  { value:'已注销', label:'已注销' }
];

interface Data {
  user_id: string
  user_name: string
  customer_name: string
  customer_sex: string
  customer_phone: string
  customer_id: string
  user_password: string
  user_status: string
}

// 不同状态不同样式
const rowClassName = ({row, rowIndex,}: {
  row: Data
  rowIndex: number
}) => {
  if (row.user_status === '在线') {
    return 'color-admin-edit-user-1';
  }
  else if (row.user_status === '离线') {
    return 'color-admin-edit-user-2';
  }
  else if (row.user_status === '已注销') {
    return 'color-admin-edit-user-3';
  }
  return '';
}

// 数据
let tableData = [];

// 条件查询
const filterTableData = ref();
function filter() {
  filterTableData.value = tableData.filter((data) =>
      (!user_id_select.value || data.user_id.toString().includes(user_id_select.value)) &&
      (!user_name_select.value || data.user_name.includes(user_name_select.value)) &&
      (!customer_name_select.value || data.customer_name.includes(customer_name_select.value)) &&
      (customer_sex_select.value === '全部' || data.customer_sex.includes(customer_sex_select.value)) &&
      (!customer_phone_select.value || data.customer_phone.includes(customer_phone_select.value)) &&
      (!customer_id_select.value || data.customer_id.includes(customer_id_select.value)) &&
      (!user_password_select.value || data.user_password.includes(user_password_select.value)) &&
      (user_status_select.value === '全部' || data.user_status.includes(user_status_select.value))
  );
}

interface UpdateRuleForm {
  user_name: string
  user_password: string
  user_password_again: string
  customer_phone: string
}

interface AddRuleForm {
  user_id: string
  user_name: string
  user_password: string
  user_password_again: string
  customer_id: string
  customer_name: string
  customer_phone: string
  customer_sex: string
}

const ruleFormRef = ref<FormInstance>();

const updateRuleForm = reactive<UpdateRuleForm>({
  user_name: '',
  user_password: '',
  user_password_again: '',
  customer_phone: ''
});

const addRuleForm = reactive<AddRuleForm>({
  user_id: '',
  user_name: '',
  user_password: '',
  user_password_again: '',
  customer_id: '',
  customer_name: '',
  customer_phone: '',
  customer_sex: ''
});

// 确认密码验证
const addPassword1 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空！'));
  }
  else {
    if (addRuleForm.user_password_again !== '') {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField('user_password_again');
    }
    callback();
  }
}
const addPassword2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('两次密码不一致！'));
  }
  else if (value !== addRuleForm.user_password) {
    callback(new Error('两次密码不一致！'));
  }
  else {
    callback();
  }
}


// 确认密码验证
const updatePassword1 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空！'));
  }
  else {
    if (updateRuleForm.user_password_again !== '') {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField('user_password_again');
    }
    callback();
  }
}
const updatePassword2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('两次密码不一致！'));
  }
  else if (value !== updateRuleForm.user_password) {
    callback(new Error('两次密码不一致！'));
  }
  else {
    callback();
  }
}

const updateRules = reactive<FormRules<UpdateRuleForm>>({
  user_name: [
    { required: true, message: '用户名不能为空！', trigger: 'blur' },
    { min: 1, max: 8, message: '1-8个字符', trigger: 'blur'}
  ],
  user_password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { validator: updatePassword1, trigger:'blur' }
  ],
  user_password_again: [
    { required: true, message: '两次密码不一致！', trigger: 'blur' },
    { validator: updatePassword2, trigger:'blur' }
  ],
  customer_phone: [
    { min: 11, max:11, message: '请输入正确的电话号码！', trigger: 'blur' }
  ]
});

const addRules = reactive<FormRules<AddRuleForm>>({
  user_id: [
    { required: true, message: '用户ID不能为空！', trigger: 'blur' }
  ],
  user_name: [
    { required: true, message: '用户名不能为空！', trigger: 'blur' },
    { min: 1, max: 8, message: '1-8个字符', trigger: 'blur'}
  ],
  user_password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { validator: addPassword1, trigger:'blur' }
  ],
  user_password_again: [
    { required: true, message: '两次密码不一致！', trigger: 'blur' },
    { validator: addPassword2, trigger:'blur' }
  ],
  customer_id: [
    { min: 18, max:18, message: '请输入正确的身份证号！', trigger: 'blur' }
  ],
  customer_phone: [
    { min: 11, max:11, message: '请输入正确的电话号码！', trigger: 'blur' }
  ]
});

const submitForm =  (formEl: FormInstance | undefined) => {
  // 提交表单
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      // 干什么！
      if(dialogVisibleUpdate.value) update();
      if(dialogVisibleAdd.value) add();
    }
  });
}

function open(id, message) {
  // 打开确认对话框
  dialogVisible.value = true;
  dialogMessage.value = message;
  user_id.value = id.toString();
}

function openUpdate(id, name) {
  // 打开修改确认对话框
  dialogVisibleUpdate.value = true;
  user_id.value = id.toString();
  updateRuleForm.user_name = name;
}

function openAdd() {
  // 打开新建确认对话框
  dialogVisibleAdd.value = true;
}

function confirm() {
  if(dialogMessage.value === '删除') Delete();
  if(dialogMessage.value === '注销') logout();
  if(dialogMessage.value === '恢复') recover();

  dialogVisible.value = false;
}

function close () {
  // 关闭确认对话框
  user_id.value = "";
  dialogMessage.value = "";
  dialogVisible.value = false;
  dialogVisibleUpdate.value = false;
  dialogVisibleAdd.value = false;
}

function init() {
  // 初始化
  instance.request({
    url: 'admin/usermanage/edituser/init',
    method: 'POST',
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "初始化失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          tableData = response.data.data;
          filterTableData.value = tableData;
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "初始化失败！",
          type: "error"
        });
        setTimeout(() => {
          init();
        }, 2000 );
      });
}

function update() {
  // 修改用户信息
  instance.request({
    url: 'admin/usermanage/edituser/update',
    method: 'POST',
    data: {
      user_id: user_id.value,
      user_name: updateRuleForm.user_name,
      user_password: updateRuleForm.user_password,
      customer_phone: updateRuleForm.customer_phone
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "修改失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_user_name") {
          ElMessage({
            message: "用户名已被使用！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "修改成功！",
            type: "success"
          });
          dialogVisibleUpdate.value = false;
        }
        init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "修改失败！",
          type: "error"
        });
      });
}

function add() {
  // 新建用户
  instance.request({
    url: 'admin/usermanage/newuser/add',
    method: 'POST',
    data: {
      user_id: addRuleForm.user_id,
      user_name: addRuleForm.user_name,
      user_password: addRuleForm.user_password,
      customer_id: addRuleForm.customer_id,
      customer_name: addRuleForm.customer_name,
      customer_phone: addRuleForm.customer_phone,
      customer_sex: addRuleForm.customer_sex
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "新建失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_user_id") {
          ElMessage({
            message: "用户ID已被使用！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_user_name") {
          ElMessage({
            message: "用户名已被使用！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "新建成功！",
            type: "success"
          });
          dialogVisibleAdd.value = false;
          init();
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "新建失败！",
          type: "error"
        });
      });
}

function Delete() {
  // 删除账号
  instance.request({
    url: 'admin/usermanage/edituser/delete',
    method: 'POST',
    data: {
      user_id: user_id.value
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "处理失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "处理成功！",
            type: "success"
          });
        }
        init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "处理失败！",
          type: "error"
        });
      });
}

function logout() {
  // 注销连接
  instance.request({
    url: 'admin/usermanage/edituser/logout',
    method: 'POST',
    data: {
      user_id: user_id.value
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "处理失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "处理成功！",
            type: "success"
          });
        }
        init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "处理失败！",
          type: "error"
        });
      });
}

function recover() {
  // 恢复账号
  instance.request({
    url: 'admin/usermanage/edituser/recover',
    method: 'POST',
    data: {
      user_id: user_id.value
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "处理失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "处理成功！",
            type: "success"
          });
        }
        init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "处理失败！",
          type: "error"
        });
      });
}
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      align-center
      width="18%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <span>确认{{ dialogMessage }}</span>
    <div class="cancel-confirm">
      <el-button color="#568fc1" plain @click="close">
        <span>取消</span>
      </el-button>

      <el-button color="#568fc1" class="button-color" @click="confirm">
        <span>确认</span>
      </el-button>
    </div>
  </el-dialog>

  <el-dialog
      v-model="dialogVisibleUpdate"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="updateRuleForm"
        :rules="updateRules"
    >
      <el-form-item label="用户名：" prop="user_name">
        <inputter width="200" v-model="updateRuleForm.user_name"/>
      </el-form-item>

      <el-form-item label="密码：" prop="user_password">
        <password width="200" v-model="updateRuleForm.user_password"/>
      </el-form-item>

      <el-form-item label="确认密码：" prop="user_password_again">
        <password width="200" v-model="updateRuleForm.user_password_again"/>
      </el-form-item>

      <el-form-item label="电话号码：" prop="customer_phone">
        <inputter width="200" v-model="updateRuleForm.customer_phone"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>

        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>修改</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="dialogVisibleAdd"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="addRuleForm"
        :rules="addRules"
    >
      <el-form-item label="用户ID：" prop="user_id">
        <inputter width="200" v-model="addRuleForm.user_id"/>
      </el-form-item>

      <el-form-item label="用户名：" prop="user_name">
        <inputter width="200" v-model="addRuleForm.user_name"/>
      </el-form-item>

      <el-form-item label="密码：" prop="user_password">
        <password width="200" v-model="addRuleForm.user_password"/>
      </el-form-item>

      <el-form-item label="确认密码：" prop="user_password_again">
        <password width="200" v-model="addRuleForm.user_password_again"/>
      </el-form-item>

      <el-form-item label="身份证号：" prop="customer_id">
        <inputter width="200" v-model="addRuleForm.customer_id"/>
      </el-form-item>

      <el-form-item label="用户实名：" prop="customer_name">
        <inputter width="200" v-model="addRuleForm.customer_name"/>
      </el-form-item>

      <el-form-item label="电话号码：" prop="customer_phone">
        <inputter width="200" v-model="addRuleForm.customer_phone"/>
      </el-form-item>

      <el-form-item label="性别：" prop="customer_sex">
        <selector width="200" :options="customer_sex_form_options" v-model="addRuleForm.customer_sex"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>

        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>新建</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <div class="select">
    <span>用户ID：</span>
    <inputter width="100" v-model="user_id_select"/>

    &emsp;&emsp;<span>用户名：</span>
    <inputter width="100" v-model="user_name_select"/>

    &emsp;&emsp;<span>用户实名：</span>
    <inputter width="100" v-model="customer_name_select"/>

    &emsp;&emsp;<span>用户性别：</span>
    <selector :options="customer_sex_options" width="100" v-model="customer_sex_select"/>

    &emsp;&emsp;<span>状态：</span>
    <selector :options="user_status_options" width="100" v-model="user_status_select"/>

    <br><br>
    <span>用户电话号码：</span>
    <inputter width="150" v-model="customer_phone_select"/>

    &emsp;&emsp;<span>用户身份证号：</span>
    <inputter width="150" v-model="customer_id_select"/>

    &emsp;&emsp;&emsp;
    <el-button color="#568fc1" class="button-color" @click="filter">
      <span>搜索</span>
    </el-button>

    &nbsp;
    <el-button color="#568fc1" class="button-color" @click="openAdd">
      <span>新建</span>
    </el-button>
  </div>
  <div class="table">
    <el-table
        header-row-style="color: #000000; background-color: #f0f0f0;"
        height="600"
        style="width: 100%"
        :data="filterTableData"
        :row-class-name="rowClassName"
    >
      <el-table-column prop="user_id" label="用户ID" width="100"/>
      <el-table-column prop="user_name" label="用户名" width="150"/>
      <el-table-column prop="customer_name" label="用户实名" width="100"/>
      <el-table-column prop="customer_sex" label="用户性别" width="100"/>
      <el-table-column prop="customer_phone" label="用户电话号码" width="200"/>
      <el-table-column prop="customer_id" label="用户身份证号" width="200"/>
      <el-table-column prop="user_password" label="用户密码" width="200"/>
      <el-table-column prop="user_status" label="状态" width="100"/>

      <el-table-column align="right" fixed="right" width="200">
        <template #default="scope">
          <el-button v-if="scope.row.user_status == '离线'"
                     color="#568fc1" class="button-color"
                     @click="openUpdate(scope.row.user_id, scope.row.user_name)">
            <span>修改</span>
          </el-button>

          <el-button v-if="scope.row.user_status === '离线'"
                     type="danger" plain
                     @click="open(scope.row.user_id, '删除')">
            <span>删除</span>
          </el-button>

          <el-button v-if="scope.row.user_status === '在线'"
                     type="danger" plain
                     @click="open(scope.row.user_id, '注销')">
            <span>注销</span>
          </el-button>

          <el-button v-if="scope.row.user_status === '已注销'"
                     type="danger" plain
                     @click="open(scope.row.user_id, '恢复')">
            <span>恢复</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.select {
  padding-top: 2vh;
  padding-left: 8vh;
  padding-right: 5vh;
  /* border: 1px solid black; */
}
.table {
  padding: 1vh 5vh 5vh;
  /* border: 1px solid black; */
}
.button-color {
  --el-button-hover-bg-color: rgb(238, 244, 249) !important;
  --el-button-hover-text-color: #568fc1 !important;
  --el-button-text-color: white !important;
}
.cancel-confirm {
  padding-top: 1vh;
  text-align: center;
}
</style>

<style>
.el-table .color-admin-edit-user-1 {
  --el-table-tr-bg-color: #80b6e5;
  --el-table-row-hover-bg-color: #80b6e5;
}
.el-table .color-admin-edit-user-2 {
  --el-table-tr-bg-color: #e4f7fb;
  --el-table-row-hover-bg-color: #e4f7fb;
}
.el-table .color-admin-edit-user-3 {
  --el-table-tr-bg-color: #f0f0f0;
  --el-table-row-hover-bg-color: #f0f0f0;
}
</style>